
from web import Session
from web.model.Agent import Agent, agentSchema
from web.model.Classify import Classify
from web.model.User import User


class Service:

    def login(self, username, password):
        session = Session()
        # 通过账号和密码进行查询
        user = session.query(User).filter(User.username == username).filter(User.password == password).first()
        session.close()
        return user

    def reg(self, user):
        session = Session()
        try:
            session.add(user)
            session.commit()
            return True
        except Exception as e:
            session.rollback()
            return False
        finally:
            session.close()

    def selectClassify(self):
        session = Session()
        classifyes = session.query(Classify).all()
        session.close()
        print(classifyes)
        return classifyes
    def addClassify(self,classify):
        session = Session()
        try:
            session.add(classify)
            session.commit()
            return True
        except Exception as e:
            session.rollback()
            return False
        session.close()

    def addAgent(self,agent):
        session = Session()
        print( agentSchema.dumps(agent))
        try:
            session.add(agent)
            session.commit()
            return True
        except Exception as e:
            # 打印异常信息
            print(e)

            session.rollback()
            return False
        finally:
            session.close()
    def selectAgent(self,classify_id = None,keyWord = None):
        session = Session()
        query = session.query(Agent)
        if classify_id:
            query = query.filter(Agent.classify_id == classify_id)
        if keyWord:
            # 根据keyword模糊查询Agent.name
            query = query.filter(Agent.name.like('%'+keyWord+'%'))
        agents = query.all()
        session.close()
        return agents

    def selectUsername(self, username):
        session = Session()
        user = session.query(User).filter(User.username == username).all()
        session.close()
        return user
